<?php
namespace App\Services\File;//服务方:负责业务逻辑处理

use App\Http\Controllers\API\FormatController;
use App\Models\FileImage;
use App\Models\Files;
use App\Services\BaseService;//服务
use App\Transformers\File\FilesTransFormer;
use Carbon\Carbon;
use http\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use TheSeer\Tokenizer\Exception;
use Throwable;

//转换:格式化

class FilesServer extends BaseService{
    private object $User;
    private Request $Request;
    private array $Header;
    private string $Lang;
    private int $Limit;
    private int $Page;
    private string $userType;

    public function __construct(FormatController $forMat)
    {
        $UserData = $forMat->getAdmin();
        if($UserData['status'] === false){
            Message(__('fail.user_not_power'));
        }
        $this->User = $UserData['user'] ?? (object)[];
        $this->Request = $forMat->getRequest();
        $this->Header = $forMat->getHeader();
        $this->Lang = $forMat->getLang();
        $this->Limit = $forMat->getLimit();
        $this->Page = $forMat->getPage();

        $this->userType = $UserData['type'];
    }

    private function Model():mixed
    {
        return Files::query()->where('user_id',$this->User->id);
    }

    /**
     * 获取图片列表
     * 可以按照
     * id,url,type,user_id,name 来搜索
     * @return array
     */
    public function list():array{//列表
        $request = $this->Request;
        $model = fn()=>self::Model();
        $data['header'] = [
            "all"=>__('file.all'),
            "image"=>__('file.types.image'),
            "document"=>__('file.types.document'),
            "audio"=>__('file.types.audio'),
            "video"=>__('file.types.video'),
            "archive"=>__('file.types.archive'),
            "text"=>__('file.types.text'),
            "code"=>__('file.types.code')
        ];
        if(!empty($request->keyword)) {//如果有关键字搜索就用关键字搜索
            $key = LikeFun($request->keyword);
            $file =$model()
                ->where('url','like',"%{$key}%")
                ->orWhere('type','like',"%{$key}%")
                ->orWhere('user_id','like',"%{$key}%")
                ->orWhere('name','like',"%{$key}%")
                ->orderByDesc('created_at')
                ->get();
        }
        elseif(!empty($request->id)) {//如果有id搜索就用id搜索
            $file =$model()
                ->where('id',$request->id)
                ->get();
        }
        else{//否则就全部搜索
            $file =$model()
                ->orderByDesc('created_at')
                ->get();
        }
        $data['files'] = $file->map(function ($res) use($data) {
            $res->type_name = $data['header'][$res->type];
            $res->url = getFileUrl($res->url);
            return FormatName($res);
            });
        $data['files_count'] = $data['files']->count();
        unset($data['header']);
        //$data['header'] = array_values($data['header']);
        return $data;

    }

    /**
     * 上传图片[注意这支持1张图片上传]
     * file:文件
     * name:文件名
     * type:文件类型
     * @return array
     */
    public function add():array{//添加（图片上传）
        $user = $this->User;
        $request = $this->Request;
        $input = $request->validate([
            'name'=>'',
            'type'=>'required|string|in:image,document,audio,video,archive,text,code'
        ],['type'=>str_replace('file',"【image,document,audio,video,archive,text,code】",__('file.file_type_error'))]);
        $input['state']=1;//状态
        $input['user_type'] = $this->userType;//用户类型
        if(!$request->hasFile('file'))Message(__('file.please_select_file'));//判断是否有文件上传
        // 获取上传的文件
        $file = $request->file('file');
        $name = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $typeArray = getFileTypeInfo($name,true);
        if($input['type'] !== $typeArray['type']) Message(str_replace('file',$typeArray['type'],__('file.is_not_allowed_file_type')));
        $input['type'] = $typeArray['type'];
        $size = (int)$file->getSize() / (1024*1024) ;
        if((float)$size > (float)$typeArray['size']){
            $size_ = (int)(float)$typeArray['size'];
             Message(__('file.image_size')." {$size_} Mb");
        }

        $input['user_id'] = $user->id;
        $time_ = time();

        //保存的文件名 M+user_id
        $time = Carbon::now()->format('Ymd');
        $time1 = Carbon::now()->format('His');
        $name = "{$time1}ali{$time_}.{$extension}";
        $file_name = "MaYi_{$input['user_id']}";

        // 保存图片到 public/uploads/file20231027 目录下
        $input['url'] = "/files/{$file_name}/{$time}/{$name}";
        $storage = Storage::disk('public')->put($input['url'], file_get_contents($file));
        if(!$storage) Message(__("file.file_upload_failed"));

        $input['url'] = setFileUrl($input['url']);
        $file_create = $this->Model()->create($input);
        if(!$file_create) Message(__("file.file_save_failed"));

        return [
            'status'=>true,
            'item'=>[
                'url'=>Storage::disk('public')->url($input['url'])
            ]
        ];
    }

    /**
     * 编辑图片[接口暂未开发]
     * @return bool
     */
    public function edit():bool{//编辑
        Message(__("file.file_not_found"));
        return true;
    }

    /**
     * 删除图片
     * url:图片url
     * id:图片id
     * @return array
     */
    public function del():array{//删除
        $request = $this->Request;
        try {
            $input = $request->validate([
                'url'=>'required|string|min:4,',
            ]);
            $file = $this->Model()->where('url',$input['url']);
        }catch (Throwable $e){
            $input = $request->validate([
                'id'=>'required|integer|min:0',
            ]);
            $file = $this->Model()->where('id',$input['id']);
        }
        if(!$file->exists())
            Message(__("file.file_not_exist"));
        $file = $file->first();
        $input['url'] = $file->url;
        $fileType_ = __("file.types.{$file->type}");
        $delete = Storage::disk('public')->delete($input['url']);

        if (!$delete)  Message(str_replace('file', $fileType_, __('file.file_del_failed')));

        $delete_db = $file->delete();
        if (!$delete_db)  Message(str_replace('file', $fileType_, __('file.file_del_data_failed')));

        return [
            'status'=>true,
            'type'=>$fileType_
        ];
    }

    public function details(){//详情

    }
}
